package com.vote.controllers;

import org.apache.log4j.Logger;

import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import com.vote.annotation.TopListRequired;
import com.vote.model.Questionnaire;
import com.vote.services.CacheService;
import com.vote.services.QuestionnaireService;

import net.paoding.rose.web.ControllerInterceptorAdapter;
import net.paoding.rose.web.Invocation;

public class TopListInterceptor extends ControllerInterceptorAdapter {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(TopListInterceptor.class);
	
	@Autowired
	CacheService cacheService;
	
	@Autowired
	QuestionnaireService questionnaireService;
	
	private String vote_hot_questionnaire_list = "vote_hot_questionnaire_list";
	private String vote_last_questionnaire_list = "vote_last_questionnaire_list";
	
    @Override
    public Class<? extends Annotation> getRequiredAnnotationClass() {
        return TopListRequired.class;
    }
	
    @Override
    public Object after(Invocation inv, Object instruction) throws Exception {
    	List<Questionnaire> hotQuestionnaireList;
    	List<Questionnaire> lastQuestionnaireList;
    	
    	hotQuestionnaireList = (List<Questionnaire>)cacheService.get(vote_hot_questionnaire_list);
    	
    	if(hotQuestionnaireList != null){
    		logger.debug("get hot list from cache~~");
    	}else{
    		hotQuestionnaireList=questionnaireService.getHotQuestionnaireList(0, 10);
    		
    		ArrayList<Questionnaire> al = new ArrayList<Questionnaire>();
    		for(Questionnaire q : hotQuestionnaireList){
    			al.add(q);
    		}
    		cacheService.set(vote_hot_questionnaire_list, al);
    		logger.debug("get hot list from database~~");
    	}
    	
    	lastQuestionnaireList = (List<Questionnaire>)cacheService.get(vote_last_questionnaire_list);
    	if(lastQuestionnaireList != null){
    		logger.debug("get last list from cache~~");
    	}else{
    		lastQuestionnaireList=questionnaireService.getNewQuestionnaireList(0, 10);
    		
    		ArrayList<Questionnaire> al = new ArrayList<Questionnaire>();
    		for(Questionnaire q : lastQuestionnaireList){
    			al.add(q);
    		}
    		
    		cacheService.set(vote_last_questionnaire_list, al);
    		boolean bb = cacheService.exist(vote_last_questionnaire_list);
    		logger.debug("get last list from database~~");
    	}
    	
		inv.addModel("hotQuestionnaire", hotQuestionnaireList);
		inv.addModel("lastQuestionnaire", lastQuestionnaireList);
        return instruction;
    }
}
